package com.example.data.factory.web1.controller;

import com.example.data.factory.common.Dto.InsertDataStandardDto;
import com.example.data.factory.common.result.R;
import com.example.data.factory.entity.entity.DataStandard;
import com.example.data.factory.service.service.DataStandardService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class DataStandardExcleController {
    @Resource
    private DataStandardService dataStandardService;

    @GetMapping("/exportDateStandard")
    public ResponseEntity<byte[]> exportExcel() {
        String fileName = "标准模板.xlsx"; // 文件名与模板一致
        byte[] bytes = exportToExcel ();

        HttpHeaders headers = new HttpHeaders ();
        headers.setContentType ( MediaType.APPLICATION_OCTET_STREAM );
        headers.setContentDispositionFormData ( "attachment", fileName );

        return ResponseEntity.ok ()
                .headers ( headers )
                .body ( bytes );
    }

    private byte[] exportToExcel() {
        Workbook workbook = new XSSFWorkbook ();
        Sheet sheet = workbook.createSheet ( "Sheet1" ); // 工作表名称与模板一致

        // ================= 表头设计 =================
        // 创建第一行表头
        Row headerRow1 = sheet.createRow ( 0 );
        createHeaderCell ( workbook, headerRow1, 0, "中文名称" );
        createHeaderCell ( workbook, headerRow1, 1, "英文名称" );
        createHeaderCell ( workbook, headerRow1, 2, "标准说明" );
        createHeaderCell ( workbook, headerRow1, 3, "是否为空" );
        createHeaderCell ( workbook, headerRow1, 4, "来源机构" );
        createHeaderCell ( workbook, headerRow1, 5, "默认值" );
        createHeaderCell ( workbook, headerRow1, 6, "数据类型" );
        createHeaderCell ( workbook, headerRow1, 7, "数据长度" );
        createHeaderCell ( workbook, headerRow1, 8, "数据精度" );
        createHeaderCell ( workbook, headerRow1, 9, "取值范围最小" );
        createHeaderCell ( workbook, headerRow1, 10, "取值范围最大" );
        createHeaderCell ( workbook, headerRow1, 11, "码表名称" );

        // ================= 列宽自适应 =================
        sheet.setColumnWidth ( 0, 4000 ); // 码表名称列宽
        sheet.setColumnWidth ( 1, 5000 ); // 码表说明列宽
        sheet.setColumnWidth ( 2, 3000 ); // 编码取值列宽
        sheet.setColumnWidth ( 3, 4000 ); // 编码名称列宽
        sheet.setColumnWidth ( 4, 6000 ); // 编码含义列宽
        sheet.setColumnWidth ( 5, 6000 ); // 编码含义列宽
        sheet.setColumnWidth ( 6, 6000 ); // 编码含义列宽
        sheet.setColumnWidth ( 7, 6000 ); // 编码含义列宽
        sheet.setColumnWidth ( 8, 6000 ); // 编码含义列宽
        sheet.setColumnWidth ( 9, 6000 ); // 编码含义列宽
        sheet.setColumnWidth ( 10, 6000 ); // 编码含义列宽
        sheet.setColumnWidth ( 11, 6000 ); // 编码含义列宽


        // ================= 输出文件 =================
        ByteArrayOutputStream out = new ByteArrayOutputStream ();
        try {
            workbook.write ( out );
        } catch (IOException e) {
            e.printStackTrace ();
        } finally {
            try {
                workbook.close ();
            } catch (IOException e) {
                e.printStackTrace ();
            }
        }

        return out.toByteArray ();
    }

    private void createHeaderCell(Workbook workbook, Row row, int columnIndex, String value) {
        CellStyle headerStyle = workbook.createCellStyle ();
        headerStyle.setAlignment ( HorizontalAlignment.CENTER );
        headerStyle.setVerticalAlignment ( VerticalAlignment.CENTER );

        // 加粗字体
        Font font = workbook.createFont ();
        font.setBold ( true );
        headerStyle.setFont ( font );

        // 加粗边框（将THIN改为MEDIUM）
        headerStyle.setBorderTop ( BorderStyle.MEDIUM );    // 上边框
        headerStyle.setBorderBottom ( BorderStyle.MEDIUM ); // 下边框
        headerStyle.setBorderLeft ( BorderStyle.MEDIUM );   // 左边框
        headerStyle.setBorderRight ( BorderStyle.MEDIUM );  // 右边框

        Cell cell = row.createCell ( columnIndex );
        cell.setCellValue ( value );
        cell.setCellStyle ( headerStyle );
    }

    @PostMapping("/importDataStandard")
    public ResponseEntity<String> importDataStandard(@RequestParam("file") MultipartFile file) {
        try (Workbook workbook = new XSSFWorkbook ( file.getInputStream () )) {
            Sheet sheet = workbook.getSheetAt ( 0 );
            for (int i = 1; i <= sheet.getLastRowNum (); i++) { // 跳过表头
                Row row = sheet.getRow ( i );
                if (row == null) continue;

                InsertDataStandardDto insertDto = mapRowToInsertDataStandardDto ( row );

                R<DataStandard> result = dataStandardService.insert ( insertDto );
                if (!"成功".equals ( result.getMsg () )) {
                    return ResponseEntity.badRequest ().body ( "第" + (i + 1) + "行数据导入失败: " + result.getMsg () );
                }
            }
            return ResponseEntity.ok ( "导入成功" );
        } catch (IOException e) {

            return ResponseEntity.status ( HttpStatus.INTERNAL_SERVER_ERROR ).body ( "导入失败: " + e.getMessage () );
        }
    }
    private InsertDataStandardDto mapRowToInsertDataStandardDto(Row row) {
        InsertDataStandardDto dto = new InsertDataStandardDto ();
        dto.setChineseName ( validateAndGetStringValue ( row.getCell ( 0 ) ) );
        dto.setEnglishName ( validateAndGetStringValue ( row.getCell ( 1 ) ) );
        dto.setDescription ( validateAndGetStringValue ( row.getCell ( 2 ) ) );
        dto.setNotNull ( validateAndGetStringValue ( row.getCell ( 3 ) ) ); // 注意：这里需要转换为Y/N
        dto.setInstitution ( validateAndGetStringValue ( row.getCell ( 4 ) ) );
        dto.setValue ( validateAndGetStringValue ( row.getCell ( 5 ) ) ); // 默认值
        dto.setDataType ( validateAndGetStringValue ( row.getCell ( 6 ) ) );
        dto.setLength ( (int) validateAndGetNumericValue ( row.getCell ( 7 ) ) ); // 注意：类型转换
        dto.setDataAccuracy ( validateAndGetNumericValue ( row.getCell ( 8 ) ) );
        dto.setMin ( validateAndGetNumericValue ( row.getCell ( 9 ) ) );
        dto.setMax ( validateAndGetNumericValue ( row.getCell ( 10 ) ) );
        dto.setDictName ( validateAndGetStringValue ( row.getCell ( 11 ) ) ); // 如果适用
        return dto;
    }

    private String validateAndGetStringValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType ()) {
            case STRING:
                return cell.getStringCellValue ();
            case NUMERIC:
                return String.valueOf ( cell.getNumericCellValue () );
            default:

                return "";
        }
    }

    private double validateAndGetNumericValue(Cell cell) {
        if (cell == null || cell.getCellType () != CellType.NUMERIC) {
              return 0;
        }
        return cell.getNumericCellValue ();
    }
}
